package me.xlgp.xiquzimu.data;

import java.util.List;

import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.ObservableSource;
import io.reactivex.rxjava3.functions.Function;
import me.xlgp.xiquzimu.config.FetchRepositoryConfig;
import me.xlgp.xiquzimu.responsebody.ChangDuanInfo;

public class FetchRemoteRepository implements IFetchRemoteRepository {

    private final IFetchRemoteRepository fetchRemoteRepository;

    public FetchRemoteRepository() {
        FetchRepositoryConfig.REPOSITORY_ENUM repositoryEnum = FetchRepositoryConfig.getRepositoryType();
        if (repositoryEnum == FetchRepositoryConfig.REPOSITORY_ENUM.GITEE) {
            fetchRemoteRepository = new FetchGiteeRepository();
        } else {
            fetchRemoteRepository = new FetchGithubRepository();
        }
    }

    @Override
    public Observable<List<String>> getNameList() {
        return fetchRemoteRepository.getNameList();
    }

    @Override
    public Observable<List<String>> changDuan(String path) {
        return fetchRemoteRepository.changDuan(path);
    }

    public Observable<ChangDuanInfo> getChangDuanInfo() {
        return getNameList().flatMap((Function<List<String>, ObservableSource<ChangDuanInfo>>) list -> {
            ChangDuanInfo changDuanInfo = new ChangDuanInfo();
            for (String s : list) {
                if (s.endsWith(".lrc")) {
                    changDuanInfo.addNameList(s.substring(1));
                } else if (s.startsWith("./")) {
                    changDuanInfo.addJuZhong(s.substring(2));
                }
            }
            return Observable.just(changDuanInfo);
        });
    }
}
